All files / src/app/api/admin/promotions/[id]/analytics route.ts

0% Statements 0/214
100% Branches 0/0
0% Functions 0/1
0% Lines 0/214

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215                                                                                                                                                                                                                                                                                                                                                                                                                                             
export const dynamic = "force-dynamic";

import { NextRequest, NextResponse } from 'next/server';
import { } from "next-auth";
import { prisma } from "@/lib/prisma";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";

interface RouteParams {
  params: Promise<{ id: string }>;
}

/**
 * GET /api/admin/promotions/[id]/analytics
 * Get analytics for a specific promotion
 */
async function handleGet(request: NextRequest,
  context: RouteContext | undefined): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;
  const promotionId = parseInt(id, 10);

  if (isNaN(promotionId)) {
    throw ApiError.badRequest("Invalid promotion ID");
  }

  // Get the promotion
  const promotion = await prisma.promotion.findUnique({
    where: { id: promotionId },
    include: {
      codes: true,
      targetProducts: {
        include: {
          product: {
            select: { id: true, title: true } } } },
      targetCategories: {
        include: {
          category: {
            select: { id: true, title: true } } } } } });

  if (!promotion) {
    throw ApiError.notFound("Promotion");
  }

  const searchParams = request.nextUrl.searchParams;
  const startDateParam = searchParams.get("startDate");
  const endDateParam = searchParams.get("endDate");

  // Default to promotion date range or last 30 days
  const endDate = endDateParam
    ? new Date(endDateParam)
    : promotion.endDate || new Date();
  const startDate = startDateParam
    ? new Date(startDateParam)
    : promotion.startDate || new Date(endDate.getTime() - 30 * 24 * 60 * 60 * 1000);

  // Get usage data
  const [usageData, , uniqueCustomers, ordersWithPromo] =
    await Promise.all([
      // All usage records for this promotion
      prisma.promotionUsage.findMany({
        where: {
          promotionId,
          usedAt: { gte: startDate, lte: endDate } },
        include: {
          user: {
            select: { id: true, name: true, email: true } },
          order: {
            select: { id: true, total: true, createdAt: true } },
          promoCode: {
            select: { code: true } } },
        orderBy: { usedAt: "desc" } }),

      // Daily usage breakdown
      prisma.promotionUsage.groupBy({
        by: ["usedAt"],
        where: {
          promotionId,
          usedAt: { gte: startDate, lte: endDate } },
        _count: true,
        _sum: {
          discountAmount: true } }),

      // Unique customers
      prisma.promotionUsage.findMany({
        where: {
          promotionId,
          usedAt: { gte: startDate, lte: endDate } },
        distinct: ["userId"],
        select: { userId: true } }),

      // Orders with this promotion
      prisma.order.findMany({
        where: {
          promotionUsages: {
            some: { promotionId } },
          createdAt: { gte: startDate, lte: endDate } },
        select: {
          id: true,
          total: true,
          createdAt: true } }),
    ]);

  // Calculate metrics
  const totalUsage = usageData.length;
  const totalDiscountGiven = usageData.reduce(
    (sum, u) => sum + (u.discountAmount || 0),
    0
  );
  const totalRevenue = ordersWithPromo.reduce((sum, o) => sum + o.total, 0);
  const avgOrderValue = totalUsage > 0 ? totalRevenue / totalUsage : 0;
  const avgDiscountPerOrder = totalUsage > 0 ? totalDiscountGiven / totalUsage : 0;

  // ROI calculation (revenue generated vs discount given)
  const roi = totalDiscountGiven > 0 ? (totalRevenue / totalDiscountGiven - 1) * 100 : 0;

  // Usage by promo code
  const codeUsage: Record<string, { count: number; discount: number }> = {};
  usageData.forEach((usage) => {
    const code = usage.promoCode?.code || "Auto-applied";
    if (!codeUsage[code]) {
      codeUsage[code] = { count: 0, discount: 0 };
    }
    codeUsage[code].count++;
    codeUsage[code].discount += usage.discountAmount || 0;
  });

  // Usage trend by day
  const usageByDay: Record<string, { count: number; discount: number; revenue: number }> = {};
  usageData.forEach((usage) => {
    const dateKey = usage.usedAt.toISOString().split("T")[0];
    if (!usageByDay[dateKey]) {
      usageByDay[dateKey] = { count: 0, discount: 0, revenue: 0 };
    }
    usageByDay[dateKey].count++;
    usageByDay[dateKey].discount += usage.discountAmount || 0;
    usageByDay[dateKey].revenue += usage.order?.total || 0;
  });

  const usageTrend = Object.entries(usageByDay)
    .map(([date, data]) => ({
      date,
      ...data }))
    .sort((a, b) => a.date.localeCompare(b.date));

  // Recent usage (last 10)
  const recentUsage = usageData.slice(0, 10).map((u) => ({
    id: u.id,
    usedAt: u.usedAt,
    discount: u.discountAmount,
    orderTotal: u.order?.total,
    orderId: u.order?.id,
    customer: u.user?.name || u.user?.email,
    promoCode: u.promoCode?.code }));

  // Conversion funnel (if we have view data - simplified for now)
  const conversionRate =
    promotion.usageLimit && promotion.usageLimit > 0
      ? (totalUsage / promotion.usageLimit) * 100
      : null;

  // Usage remaining
  const usageRemaining = promotion.usageLimit
    ? Math.max(0, promotion.usageLimit - promotion.usageCount)
    : null;

  const analytics = {
    promotion: {
      id: promotion.id,
      name: promotion.name,
      displayName: promotion.displayName,
      type: promotion.type,
      discountType: promotion.discountType,
      discountValue: promotion.discountValue,
      isActive: promotion.isActive,
      startDate: promotion.startDate,
      endDate: promotion.endDate,
      usageLimit: promotion.usageLimit,
      usageCount: promotion.usageCount,
      usageRemaining,
      targetType: promotion.targetType,
      targetProducts: promotion.targetProducts.map((tp) => tp.product),
      targetCategories: promotion.targetCategories.map((tc) => tc.category) },
    summary: {
      totalUsage,
      uniqueCustomers: uniqueCustomers.length,
      totalDiscountGiven,
      totalRevenue,
      avgOrderValue,
      avgDiscountPerOrder,
      roi,
      conversionRate },
    codePerformance: Object.entries(codeUsage)
      .map(([code, data]) => ({
        code,
        usageCount: data.count,
        totalDiscount: data.discount,
        avgDiscount: data.count > 0 ? data.discount / data.count : 0 }))
      .sort((a, b) => b.usageCount - a.usageCount),
    usageTrend,
    recentUsage,
    dateRange: {
      startDate: startDate.toISOString(),
      endDate: endDate.toISOString() } };

  return successResponse(analytics);
}

export const GET = withErrorHandling(withAdmin(handleGet));